from mtp.model import *
from mtp.model import ObjBase
from mtp.lib.plugin import Plugin


TagsTable = Table('page_tags', plugin_meta,
    Column('id', Integer, primary_key=True, autoincrement=True),
    Column('object_type', String(50)),
    Column('object_id', Integer, ForeignKey(PagesTable.c.id)),
    Column('tag', String(100)),
)


class Tag(ObjBase):
    @classmethod
    def get(klass, object_type, object_id):
        return (Session.query(klass)
                .filter(klass.object_type == object_type)
                .filter(klass.object_id == object_id)
                .order_by(klass.tag)
        )

    @classmethod
    def hasTag(klass, object_type, object_id, tag):
        return (Session.query(klass)
                .filter(klass.object_type == object_type)
                .filter(klass.object_id == object_id)
                .filter(klass.tag == tag)
                .count()
        )

    @classmethod
    def add(klass, object_type, object_id, tag):
        if Tag.hasTag(object_type, object_id, tag):
            return 
        tag = klass(object_type=object_type, object_id=object_id, tag=tag)
        tag.save()
        return tag

    @classmethod
    def remove(klass, object_type, object_id, tag):
        tag = (Session.query(klass)
                .filter(klass.object_type == object_type)
                .filter(klass.object_id == object_id)
                .filter(klass.tag == tag)
        ).one()
        tag.delete()

    @classmethod
    def find(klass, object_type, tags):
        q = Session.query(klass).filter(klass.object_type==object_type)
        
        filt = (klass.tag == tags[0])    
        for tag in tags[1:]:
            # are likes just as fast as == ?
            if '%' in tag:
                filt = filt | (klass.tag.like(tag))
            else:
                filt = filt | (klass.tag == tag)

        q = q.filter(filt)
        return q

mapper(Tag, TagsTable)

class TagClass(Tag):
    object_type = None

    @classmethod
    def get(klass, object_id):
        return Tag.get(klass.object_type, object_id)

    @classmethod
    def hasTag(klass, object_id, tag):
        return Tag.hasTag(klass.object_type, object_id, tag)

    @classmethod
    def add(klass, object_id, tag):
        return Tag.add(klass.object_type, object_id, tag)

    @classmethod
    def find(klass, tags):
        return Tag.find(klass.object_type, tags)


class TagsPlugin(Plugin):
    tables = [TagsTable]

